<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>

      </div>
      <!-- 放置table组件 -->
      <el-table :data="rolelist">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editObj.name" type="text" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="启用">
          <template #default="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editObj.state" :active-value="1" :inactive-value="0" size="mini" />
            <span v-else> {{ row.state===1?'已启用':'未启用' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editObj.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{row}">
            <el-row v-if="row.isEdit" type="flex" justify="center">
              <el-col :span="5"> <el-button type="primary" @click="sureedit(row)">确定</el-button></el-col>
              <el-col :span="3"> <el-button @click="row.isEdit=false">取消</el-button></el-col>
            </el-row>
            <el-row v-else type="flex" justify="center">
              <el-col :span="3"><el-button type="text" @click="givepower(row.id)">分配权限</el-button></el-col>
              <el-col :span="3"> <el-button type="text" @click="editrole(row)">编辑</el-button></el-col>
              <el-popconfirm title="这是一段内容确定删除吗？" @confirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" type="text">删除</el-button>
              </el-popconfirm>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination :page-size="pageParams.pagesize" :current-page="pageParams.page" :total="pageParams.total" layout="prev, pager, next" @current-change="changePage" />
      </el-row>
      <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="btnCancel">
        <!-- 表单内容 -->
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item prop="name" label="角色名称">
            <el-input v-model="roleForm.name" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item label="启用">
            <!-- 如果不需要校验 就不需要写 prop属性 -->
            <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
          </el-form-item>
          <el-form-item prop="description" label="角色描述">
            <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
                <el-button size="mini" @click="btnCancel">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog title="分配权限" :visible.sync="showpower" width="30%">
        <el-tree ref="tree" :data="powerlist" :props="{label:'name'}" node-key="id" show-checkbox default-expand-all check-strictly :default-checked-keys="permIds" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="showpower = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getroles, addRole, editRole, delRole, getRoledetail, distributepower } from '@/api/role'
import { gettree } from '@/utils/gettree'
import { getPermissionList } from '@/api/permission'
export default {
  name: 'Role',
  data() {
    return {
      showpower: false,
      currentid: '',
      permIds: [],
      powerlist: [],
      rolelist: [],
      showDialog: false,
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getrole()
  },
  methods: {
    async submit() {
      await distributepower({ id: this.currentid, permIds: this.$refs.tree.getCheckedKeys() })
      this.$message.success('分配成功')
      this.showpower = false
    },
    async givepower(id) {
      this.currentid = id
      this.powerlist = gettree(await getPermissionList(), 0)
      const { permIds } = await getRoledetail(id)
      this.permIds = permIds
      this.showpower = true
    },
    async getrole() {
      const res = await getroles(this.pageParams)
      console.log(res)
      this.pageParams.total = res.total
      this.rolelist = res.rows
      this.rolelist.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editObj', { name: item.name, state: item.state, description: item.description })
      })
    },
    async confirmDel(id) {
      await delRole(id) // 后端删除
      this.$message.success('删除角色成功')
      // 删除的如果是最后一个
      if (this.rolelist.length === 1 && this.pageParams.page > 1) this.pageParams.page--
      this.getrole()
    },
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值当前页码
      this.getrole()
    },
    btnOK() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.getrole()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.$refs.roleForm.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    editrole(row) {
      row.isEdit = true
      row.editObj.name = row.name
      row.editObj.state = row.state
      row.editObj.description = row.description
    },
    async sureedit(row) {
      // console.log(1)
      if (row.editObj.name && row.editObj.description) {
        await editRole({ ...row.editObj, id: row.id })
        Object.assign(row, { ...row.editObj, isEdit: false })
        this.$message.success('更新成功')
      } else {
        this.$message.warning('请输入角色名和描述')
      }
    }
  }
}
</script>
<style scoped lang="scss">
.role-operate {
  padding: 10px;
}
</style>
